<template>
  <a-card :bordered="false">

    <!-- 查询区域 -->
    <search ref='search' :config='searchConfig' @search='search' @getHeight='getHeight' />

    <!--地图界面-->
    <div id="container" :loading="loading"></div>

  </a-card>
</template>
<script>
  import {addRole, editRole} from "@api/api";
  import {postAction} from "@api/manage";
  import {PageListMixin} from '@/mixins/PageListMixin';
  import JSelectUserPosition from '../../../components/cn-select-popup/JSelectUserPosition';

  const MapKey = 'IXMBZ-FRWCV-RNWPB-UMWZW-ZIREO-GUB4U'

  export default {
    name: 'SfaVisitLineList',
    mixins: [PageListMixin],
    components: {
      JSelectUserPosition
    },
    data() {
      return {
        //查询区域
        searchConfig:[
          {
            type: 'input',
            name: 'visitPosCode',
            placeholder: '选择人员'
          },
          {
            type: 'date',
            name: 'tempVisitDate',
            placeholder: '请选择日期'
          },
        ],
        position: [],
        polylineLayer: null,
        paths: [],
        map: null,
        loading: null,
        points: [
          {
            lat: 39.984120,
            lng: 116.307484
          },
        ],

        url: {
          getListLatAndLng: window._CONFIG['domianSfaURL'] + '/visit/sfaVisitLineController/getListLatAndLng',
        }
      }
    },
    methods: {
      searchQuery() {
        if (!this.url.getListLatAndLng) {
          this.$message.error("请设置url!")
          return;
        }
        var that = this;
        that.loading = true;
        let param = {...this.queryParam}
        // console.log(param)
        postAction(this.url.getListLatAndLng, param).then((res) => {
          if (res.success) {
            if (res.result.length > 0) {
              that.$message.success(res.message);
              //销毁地图
              that.map.destroy()
              that.paths = [];
              //创建地图
              that.initMap(res.result)
              // console.log(res)
            } else {
              that.$message.warning('路线未规划!');
            }
          } else {
            that.$message.warning(res.message);
          }
          that.loading = false;
        });
      },
      searchReset(){
        this.queryParam = []
        //销毁地图
        this.map.destroy()
        this.paths = [];
        //创建地图
        this.initMap(this.points)
      },
      loadScript() {
        if (document.querySelector('#MapTools')) return Promise.resolve(TMap)
        return new Promise(resolve => {
          var script = document.createElement("script");
          script.id = "MapTools"
          script.type = "text/javascript";
          // libraries=tools&v=1.exp&
          script.src = `https://map.qq.com/api/gljs?libraries=tools,geometry&key=${MapKey}`;
          document.body.appendChild(script);
          script.onload = function (e) {
            resolve(TMap)
          }
          script.onreadystatechange = function (e) {
            resolve(TMap)
          }
        })
      },
      initMap(arr) {
        Promise.all([this.loadScript()]).then(() => {
          //定义地图中心点坐标
          var center = new TMap.LatLng(arr[0].lat, arr[0].lng)
          // //定义map变量，调用 TMap.Map() 构造函数创建地图
          this.map = new TMap.Map(
            document.getElementById("container"),
            {
              center: center,
              zoom: 10
            }
          );
          for (var i = 0; i < arr.length; i++) {
            var data = arr[i];
            this.paths.push(new TMap.LatLng(data.lat, data.lng))
            var title = "进店时间:"+data.createDateTime+'<br/>'+"离店时间:"+data.updateDateTime
            //初始化marker
            var marker = new TMap.MultiMarker({
              map: this.map,
              styles: { //点标注的相关样式
                "marker": new TMap.MarkerStyle({
                  "width": 25,
                  "height": 35,
                  "anchor": {x: 16, y: 32},
                  "src": 'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/markerNew.png'
                })
              },
              geometries: [{ //点标注数据数组
                "id": i,
                "styleId": "marker",
                "position": new TMap.LatLng(data.lat, data.lng),
                "properties": {
                  "title": title
                }
              }],
            })
            //初始化infoWindow
            var infoWindow = new TMap.InfoWindow({
              map: this.map,
              position: new TMap.LatLng(data.lat, data.lng),
              offset: {x: 0, y: -32} //设置信息窗相对position偏移像素，为了使其显示在Marker的上方
            });
            infoWindow.close();//初始关闭信息窗关闭
            //监听标注点击事件
            marker.on("click", function (evt) {
              //设置infoWindow
              infoWindow.open(); //打开信息窗
              infoWindow.setPosition(evt.geometry.position);//设置信息窗位置
              infoWindow.setContent(evt.geometry.properties.title);//设置信息窗内容
            })
            //初始化label
            var label = new TMap.MultiLabel({
              map: this.map, //设置折线图层显示到哪个地图实例中
              //文字标记样式
              styles: {
                'label': new TMap.LabelStyle({
                  'color': '#3777FF', //颜色属性
                  'size': 15, //文字大小属性
                  'offset': {x: 0, y: 0}, //文字偏移属性单位为像素
                  'angle': 0, //文字旋转属性
                  'alignment': 'center', //文字水平对齐属性
                  'verticalAlignment': 'middle' //文字垂直对齐属性
                })
              },
              //文字标记数据
              geometries: [{
                'id': i, //点图形数据的标志信息
                'styleId': 'label', //样式id
                'position': new TMap.LatLng(data.lat, data.lng), //标注点位置
                'content': data.clientName, //标注文本
              }]
            });
          }
          //创建 MultiPolyline
          var polylineLayer = new TMap.MultiPolyline({
            id: 'polyline-layer', //图层唯一标识
            map: this.map,//设置折线图层显示到哪个地图实例中
            //折线样式定义
            styles: {
              'style_blue': new TMap.PolylineStyle({
                'color': '#3777FF', //线填充色
                'width': 6, //折线宽度
                'borderWidth': 5, //边线宽度
                'borderColor': '#FFF', //边线颜色
                'lineCap': 'butt' //线端头方式
              })
            },
            //折线数据定义
            geometries: [
              {//第1条线
                'id': 'pl_1',//折线唯一标识，删除时使用
                'styleId': 'style_blue',//绑定样式名
                'paths': this.paths
              }
            ]
          });
        })
      }
    },
    mounted() {
      // this.Tmap()
      this.initMap(this.points)
    }

  }
</script>
<style scoped>
  @import '~@assets/less/common.less';

</style>
